package com.chen.Dome1create;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class ThreadDome3 {
    public static void main(String[] args) {
        //目标：实现Callable接口,优势：可以有返回值，可以抛出异常

        MyCallable mc = new MyCallable(100);
        //3.创建Thread对象，把Callable接口的实现类对象作为构造参数传递
        FutureTask<String> t1 = new FutureTask<>(mc);
        /*
        * 1.FutureTask是RunnableFuture接口的实现类
        * 未来任务对象的作用：
        * 1.可以包装为Thread对象
        * 2.本质上是Runnable接口的实现类
         */
        //4.调用start方法，启动线程
        new Thread(t1).start();//线程启动

        MyCallable mc1 = new MyCallable(3);
        FutureTask<String> t2 = new FutureTask<>(mc1);
        new Thread(t2).start();//线程启动

        //5.获取线程执行结果
        try {
            //如果发现线程执行结果还没有准备好，则阻塞等待
            String result = t1.get();
            System.out.println(result);
            String result1 = t2.get();
            System.out.println(result1);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

class MyCallable implements Callable<String> {
    private int n;

    public MyCallable(int n) {
        this.n = n;
    }

    public String call() throws  Exception {
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        return "result=1-"+n+"的和为"+sum;
    }
}
